import { isEmpty, isString } from 'lodash';

export const getAreaId = (level, areaColors) => {
  let id = '';
  areaColors.forEach(({ start, end, color }, idx) => {
    if (level >= start && level <= end) {
      id = `${color}_${idx}`;
    }
  });
  return id;
};

export const getAreaColor = (level, areaColors) => {
  const hit = areaColors.find(
    ({ start, end }) => (level >= start && level <= end)
  );
  return hit ? hit.color : '#053556';
};

// 数据格式化为geoJson
export const conversionGeoData = (data) => {
  if (isEmpty(data)) return [];
  return {
    type: 'FeatureCollection',
    features: data
      .filter(item => Array.isArray(item.coords)
        && Array.isArray(item.coords[0])
        && Array.isArray(item.coords[0][0])
        && (!item.type || isString(item.type)))
      .map(item => ({
        type: 'Feature',
        properties: {
          id: item.id,
          name: item.name || '',
          tooltip: item.info || '',
          value: Number(item.value) || 0
        },
        geometry: {
          type: item.type || 'Polygon',
          coordinates: item.coords
        }
      })),
    features1: []
  };
};

export const geoJSONStyle = (backgroundInnerColor) => ({
  color: '#1f2021',
  weight: 1,
  fillOpacity: 0.3,
  fillColor: backgroundInnerColor,
});

// 计算高宽比例
export const colcWHPercentage = (w, h) => {
  const baseWP = Math.floor((w / h) * 100);
  let wp = baseWP / 100;
  const baseHP = Math.floor((h / w) * 100);
  let hp = baseHP / 100;

  if (w < h) {
    const c = Math.floor((hp - wp) * 100) / 100;
    if (c === 1.08) {
      // 陕西省
      wp = baseWP / 100 + 0.54;
      hp = baseHP / 100 + 0.2;
    } else if (c > 0.8) {
      wp = baseWP / 100 + 0.4;
    } else if (c > 0.5) {
      wp = baseWP / 100 + 0.2;
    } else if (c > 0.2) {
      wp = baseWP / 100 + 0.1;
    }
  } else {
    const c = Math.floor((wp - hp) * 100) / 100;
    hp = baseHP / 100 + (c / 2);
    if (c === 1.3) {
      // 西藏自治区
      hp = baseHP / 100 + 0.5;
    }
    if (c === 0.63 || c === 0.65) {
      // 中国、南通市
      hp = baseHP / 100 + 0.27;
    }
    if (c === 0.48) {
      // 甘肃省
      hp = baseHP / 100 + 0.24;
    }
    if (c === 0.26 || c === 0.3 || c === 0.28) {
      // 乌鲁木齐市、四川省、贵阳市
      hp = baseHP / 100 + 0.15;
    }
  }
  return {
    wp,
    hp
  };
};
